package top.sqdpt.rag.store;

import com.alibaba.fastjson2.JSON;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import top.sqdpt.rag.entity.VxChatMessage;
import top.sqdpt.rag.service.VxChatMessageService;

import java.util.ArrayList;
import java.util.List;

@Component
public class MysqlChatStore implements ChatMemoryStore {

    @Autowired
    private VxChatMessageService vxChatMessageService;

    @Override
    public List<ChatMessage> getMessages(Object chatId) {
        VxChatMessage vxChatMessage = vxChatMessageService.lambdaQuery().eq(VxChatMessage::getChatId, chatId).one();
        if (vxChatMessage == null) {
            return new ArrayList<>();
        }
        String chatMessage = vxChatMessage.getChatMessage();
        if (!StringUtils.hasText(chatMessage)) {
            return new ArrayList<>();
        }
        return JSON.parseArray(chatMessage, ChatMessage.class);
    }

    @Override
    public void updateMessages(Object chatId, List<ChatMessage> list) {
        vxChatMessageService.lambdaUpdate().eq(VxChatMessage::getChatId, chatId).set(VxChatMessage::getChatMessage, JSON.toJSONString(list)).update();
    }

    @Override
    public void deleteMessages(Object chatId) {
        vxChatMessageService.lambdaUpdate().eq(VxChatMessage::getChatId, chatId).remove();
    }
}
